package com.kco.generate.app;

import com.kco.generate.config.ColumnsBean;
import com.kco.generate.config.TableBean;
import com.kco.generate.config.Utils;

/**
 * Created by 666666 on 2017/11/6.
 */
public class CreateListComponentTs {
    public static void buildFile(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        sb.append(buildImport(tableBean))
                .append(buildClassHeader(tableBean))
                .append(buildClassField(tableBean))
                .append(buildClassInit(tableBean))
                .append(buildClassEvent(tableBean))
                .append(buildClassFooter(tableBean));
        String className = tableBean.getClassName();
        String fileName = className.substring(0, 1).toLowerCase() + className.substring(1);
        Utils.saveFile("js/"+fileName+"/" + fileName + "-list.component.ts", sb.toString());
    }

    private static String buildClassFooter(TableBean tableBean) {
        String className = tableBean.getClassName();
        String tempName = className.substring(0, 1).toLowerCase() + className.substring(1);
        StringBuilder sb = new StringBuilder();
        return "}\n";
    }

    private static String buildClassEvent(TableBean tableBean) {
        String className = tableBean.getClassName();
        String tempName = className.substring(0, 1).toLowerCase() + className.substring(1);
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        for (ColumnsBean columnsBean : tableBean.getColumnsBeans()) {
            sb1.append("      "+columnsBean.getPropertyName()+": '',\n");
        }
        sb.append("// =============== start 成员方法  ======================\n" +
                "  /**\n" +
                "   * 分页查询"+tableBean.getTableComment()+"列表\n" +
                "   */\n" +
                "  list"+className+"OnPage(event:any = null) {\n" +
                "    this.pageNo = (event && event.first / event.rows + 1) || 1;\n" +
                "    this.pageSize = (event && event.rows) || this.pageSize;\n" +
                "\n" +
                "    this."+tempName+"Service.list"+className+"(this.searchParam, this.pageNo, this.pageSize)\n" +
                "      .then(data => {\n" +
                "        this.totalRecords = data.count;\n" +
                "        this."+tempName+"List = data.data;\n" +
                "      });\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 重置查询条件\n" +
                "   */\n" +
                "  resetSearchParam(){\n" +
                "    this.searchParam = {}\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 跳转"+tableBean.getTableComment()+"详情页\n" +
                "   */\n" +
                "  to"+className+"DetailsPage("+tableBean.getPrimaryPropertyKey()+":string){\n" +
                "    this.router.navigate(['/app/"+tempName+"/"+tempName+"Details', "+tableBean.getPrimaryPropertyKey()+"]);\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 删除"+tableBean.getTableComment()+"\n" +
                "   * @param selected"+className+"\n" +
                "   */\n" +
                "  private delete"+className+"(selected"+className+": any) {\n" +
                "    if (!selected"+className+"){\n" +
                "      this.messageService.add(\n" +
                "        {severity:'warn', summary:'系统消息', detail:'请选择需要删除的"+tableBean.getTableComment()+"'}\n" +
                "      );\n" +
                "      return;\n" +
                "    }\n" +
                "    this.confirmationService.confirm({\n" +
                "      message: `是否删除"+tableBean.getTableComment()+":${selected"+className+"."+tableBean.getPrimaryPropertyKey()+"}`,\n" +
                "      header: '删除"+tableBean.getTableComment()+"',\n" +
                "      accept: () => {\n" +
                "        this."+tempName+"Service.delete"+className+"(selected"+className+"."+tableBean.getPrimaryPropertyKey()+").then(\n" +
                "          data => {\n" +
                "            this.messageService.add({\n" +
                "              severity: data.success ? 'success' : 'error',\n" +
                "              summary:'系统消息',\n" +
                "              detail:data.success ? `成功删除"+tableBean.getPrimaryPropertyKeyColumnComment()+"'${selected"+className+"."+tableBean.getPrimaryPropertyKey()+"}'` : `删除失败-${data.message}`}\n" +
                "            );\n" +
                "            data.success && this.list"+className+"OnPage();\n" +
                "          }\n" +
                "        );\n" +
                "      }\n" +
                "    });\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 重置新增/修改弹出框的关联值\n" +
                "   */\n" +
                "  resetTheOperation"+className+"(){\n" +
                "    this.theOperation"+className+" = {\n" +
                sb1.toString() +
                "      icon: 'fa-plus'\n" +
                "    };\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 展示新增"+tableBean.getTableComment()+"的弹出框\n" +
                "   */\n" +
                "  private showAdd"+className+"Dialog() {\n" +
                "    this.diaLog = {\n" +
                "      title: '新增"+tableBean.getTableComment()+"',\n" +
                "      display: true,\n" +
                "      isAddModal: true\n" +
                "    };\n" +
                "    this.theOperation"+className+" = {};\n" +
                "    this.resetSearchParam();\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 展示更新"+tableBean.getPrimaryPropertyKeyColumnComment()+"的弹出框\n" +
                "   */\n" +
                "  private showUpdate"+className+"Dialog(selected"+className+": any) {\n" +
                "    if (!selected"+className+"){\n" +
                "      this.messageService.add(\n" +
                "        {severity:'warn', summary:'系统消息', detail:'请选择需要更新的"+tableBean.getTableComment()+"'}\n" +
                "      );\n" +
                "      return;\n" +
                "    }\n" +
                "    this.diaLog = {\n" +
                "      title: '修改"+tableBean.getTableComment()+"',\n" +
                "      display: true,\n" +
                "      isAddModal: false\n" +
                "    };\n" +
                "    this.theOperation"+className+" = selected"+className+";\n" +
                "  }\n" +
                "\n" +
                "  /**\n" +
                "   * 新增/修改"+tableBean.getTableComment()+"\n" +
                "   * @param selected"+className+"\n" +
                "   */\n" +
                "  insertOrUpdate(selected"+className+": any){\n" +
                "    let that = this;\n" +
                "    this.confirmationService.confirm({\n" +
                "      message: `是否提交操作`,\n" +
                "      header: this.diaLog.isAddModal ? '新增"+tableBean.getTableComment()+"': '更新"+tableBean.getTableComment()+"',\n" +
                "      accept: () => {\n" +
                "        let insertOrUpdate = that.diaLog.isAddModal ?\n" +
                "          that."+tempName+"Service.insert"+className+"(that.theOperation"+className+") :\n" +
                "          that."+tempName+"Service.update"+className+"(that.selected"+className+"."+tableBean.getPrimaryPropertyKey()+", that.theOperation"+className+");\n" +
                "        insertOrUpdate.then(data => {\n" +
                "          that.messageService.add({\n" +
                "            severity: data.success ? 'success' : 'error',\n" +
                "            summary:'系统消息',\n" +
                "            detail: data.success ? `操作成功` : `操作失败-${data.message}`}\n" +
                "          );\n" +
                "          if (data.success){\n" +
                "            that.resetTheOperation"+className+"();\n" +
                "            that.list"+className+"OnPage();\n" +
                "            that.selected"+className+" = null;\n"+
                "            that.diaLog.display = false;\n" +
                "          }\n" +
                "        });\n" +
                "      }\n" +
                "    });\n" +
                "  }\n" +
                "  // =============== end 成员方法  ========================\n\n\n");
        return sb.toString();
    }

    private static String buildClassInit(TableBean tableBean) {
        String className = tableBean.getClassName();
        String tempName = className.substring(0, 1).toLowerCase() + className.substring(1);
        StringBuilder sb = new StringBuilder();
        sb.append("  // =============== start 构造器和初始化 =================\n" +
                "  constructor(\n" +
                "    private "+tempName+"Service: "+className+"Service,\n" +
                "    private mainService: MainService,\n" +
                "    private router: Router,\n" +
                "    private messageService: MessageService,\n" +
                "    private confirmationService: ConfirmationService,\n" +
                "    private commonService: CommonService\n" +
                "  ) {}\n" +
                "  ngOnInit(): void {\n" +
                "    this.mainService.menuItemNext(this.commonService.breadcrumb."+tempName+"List);\n" +
                "    this.list"+className+"OnPage();\n" +
                "    this.menubarItems = [\n" +
                "      {label: '新增', icon: 'fa-plus', command: (event) => this.showAdd"+className+"Dialog()},\n" +
                "      {label: '修改', icon: 'fa-pencil', command: (event) => this.showUpdate"+className+"Dialog(this.selected"+className+")},\n" +
                "      {label: '删除', icon: 'fa-close', command: (event) => this.delete"+className+"(this.selected"+className+")}\n" +
                "    ];\n" +
                "    this.resetTheOperation"+className+"();\n" +
                "  }\n" +
                "  // =============== end 构造器和初始化 ===================\n\n\n");
        return sb.toString();
    }

    private static String buildClassField(TableBean tableBean) {
        String className = tableBean.getClassName();
        String tempName = className.substring(0, 1).toLowerCase() + className.substring(1);
        StringBuilder sb = new StringBuilder();
        sb.append("\n" +
                "  // =============== start 成员变量 =======================\n" +
                "  // 顶部菜单条\n" +
                "  menubarItems: MenuItem[];\n" +
                "  // 被选中的"+tableBean.getTableComment()+"\n" +
                "  selected"+className+": any;\n" +
                "\n" +
                "  // "+tableBean.getTableComment()+"列表信息\n" +
                "  "+tempName+"List: Array<any>;\n" +
                "  // "+tableBean.getTableComment()+"列表总数\n" +
                "  totalRecords: number = 0;\n" +
                "  // "+tableBean.getTableComment()+"列表查询条件\n" +
                "  searchParam: any = {};\n" +
                "  // 分页页码\n" +
                "  pageNo = 1;\n" +
                "  // 分页页数\n" +
                "  pageSize = 5;\n" +
                "  // 新增/修改的"+tableBean.getTableComment()+"信息\n" +
                "  theOperation"+className+":any;\n" +
                "  // 新增/修改"+tableBean.getTableComment()+"弹出框配置\n" +
                "  diaLog: any ={\n" +
                "    title: '新增"+tableBean.getTableComment()+"',\n" +
                "    display: false,\n" +
                "    isAddModal: true\n" +
                "  };\n" +
                "  // =============== end 成员变量 =========================\n\n\n");
        return sb.toString();
    }

    private static String buildClassHeader(TableBean tableBean) {
        String className = tableBean.getClassName();
        String tempName = className.substring(0, 1).toLowerCase() + className.substring(1);
        StringBuilder sb = new StringBuilder();
        sb.append("@Component({\n" +
                "  selector: 'bz-"+tempName+"-list',\n" +
                "  templateUrl: './"+tempName+"-list.component.html'\n" +
                "})\n" +
                "export class "+className+"ListComponent implements OnInit{\n");
        return sb.toString();
    }

    private static String buildImport(TableBean tableBean) {
        String className = tableBean.getClassName();
        String tempName = className.substring(0, 1).toLowerCase() + className.substring(1);
        StringBuilder sb = new StringBuilder();
        sb.append("import {Component, OnInit} from \"@angular/core\";\n" +
                "import {"+className+"Service} from \"./"+tempName+".service\";\n" +
                "import {MainService} from \"../main/main-service\";\n" +
                "import {Router} from \"@angular/router\";\n" +
                "import {MenuItem} from \"primeng/primeng\";\n" +
                "import {MessageService} from \"primeng/components/common/messageservice\";\n" +
                "import {CommonService} from \"../utils/common.service\";\n" +
                "import {ConfirmationService} from \"primeng/components/common/confirmationservice\";\n");
        return sb.toString();
    }
}
